package com.liuqi.openai.keyword;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2025/8/3
 **/
public class DictionaryUtil {

    /**
     * 注释
     */
    private final static String ANNOTATION_SYMBOLS = "#";

    /**
     * 表示空字符
     */
    private final static String NULL_SYMBOLS = "NULL";

    /**
     * 加载关键词词典
     *
     * @param file  关键词词典文件路径
     */
    public static List<Dictionary> loadDict(File file) throws FileNotFoundException {
        return loadDict(new FileInputStream(file));
    }

    /**
     * 加载关键词词典
     *
     * @param is
     */
    public static List<Dictionary> loadDict(InputStream is) {
        if (is == null) {
            throw new NullPointerException("load dict, InputStream cannot be null");
        }
        String pre = null;
        List<Dictionary> dictionaries = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            while (br.ready()) {
                String line = br.readLine().trim();
                if (line.startsWith(ANNOTATION_SYMBOLS)) continue;
                if (line.isEmpty()) continue;
                String[] tokens = line.split("[\t ]+");
                if (tokens.length == 0) continue;

                String keyword = tokens[0].trim();
                String posTag = null;
                String[] related = null;
                boolean stop = false;
                if (tokens.length > 1) posTag = tokens[1].trim();
                if (tokens.length > 2) {
                    String str = tokens[2].trim();
                    if (!NULL_SYMBOLS.equals(str)) {
                        related = tokens[2].split(",");
                    }
                }
                if (tokens.length > 3) stop = Boolean.parseBoolean(tokens[3].trim());
                pre = keyword;

                dictionaries.add(
                        new Dictionary(keyword, posTag, related, stop)
                );
            }

            return dictionaries;
        } catch (Throwable t) {
            String fail = "failed to load keyword dictionary.";
            if (pre == null) {
                fail += "on the first line of the keyword";
            } else {
                fail += "Error next to keyword [" + pre + "]";
            }
            throw new RuntimeException(fail, t);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (Throwable t) { }
        }
    }

}
